package com.ylp.sys.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ylp.common.exception.ServiceException;
import com.ylp.common.response.Result;
import com.ylp.sys.auth.entity.UserInfo;
import com.ylp.sys.domain.entity.SysMenu;
import com.ylp.sys.domain.vo.MenuVo;
import com.ylp.sys.domain.vo.RouterVO;
import com.ylp.sys.service.SysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统菜单表 前端控制器
 * </p>
 *
 * @author cc
 * @since 2024-07-24
 */
@Tag(name = "系统菜单接口")
@RestController
@RequestMapping("/menu")
public class SysMenuController {
    private final SysMenuService menuService;

    public SysMenuController(SysMenuService menuService) {
        this.menuService = menuService;
    }

    @Operation(summary = "查询当前用户菜单")
    @GetMapping("/getSelfMenu")
    public Result<List<RouterVO>> getSelfMenu() {
        UserInfo userLoginInfo = (UserInfo) StpUtil.getSession().get("userInfo");
        Long id = userLoginInfo.getId();
        return Result.success(menuService.getMenuByUserId(id));
    }

    @Operation(summary = "查询菜单树")
    @GetMapping("/treeselect")
    public Result<List<Map<String, Object>>> treeselect() {
        return Result.success(menuService.treeselect());
    }

    @Operation(summary = "获取菜单表，层级")
    @PostMapping("/listTree")
    public Result<List<MenuVo>> listTree(@RequestBody SysMenu menu) {
        return Result.success(menuService.getListTree(menu));
    }

    @Operation(summary = "添加菜单")
    @PostMapping("/add")
    public Result<String> add(@RequestBody SysMenu menu) {
        try{
            menuService.addMenu(menu);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("添加失败");
        }
        return Result.success();
    }

    @Operation(summary = "修改菜单")
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody SysMenu menu) {
        try {
            menuService.editMenu(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
        return Result.success();
    }

    @Operation(summary = "根据id获取menu")
    @GetMapping("/getMenuById")
    public Result<SysMenu> getMenuById(@RequestParam Long id) {
        return Result.success(menuService.getMenuById(id));
    }

    @Operation(summary = "删除菜单")
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable("id") Long id) {
        try {
            menuService.deleteMenuCheckChildAndRole(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return Result.success();
    }



}

